package com.s64.ch08.modules.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.s64.ch08.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
public class LoginUser implements UserDetails {
    private User user;
    private Set<String> roleKeyList;
    private Set<String> permsList;

    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        /*for (String perms : permsList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perms);
            list.add(authority);
        }
        for (String role : roleKeyList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
            list.add(authority);
        }*/
        list.addAll(permsList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        list.addAll(roleKeyList.stream().map(item -> new SimpleGrantedAuthority("ROLE_" + item)).collect(Collectors.toList()));
        return list;
    }

    public Set<String> getPermsList() {
        return permsList;
    }

    public void setPermsList(Set<String> permsList) {
        this.permsList = permsList;
    }

    public Set<String> getRoleKeyList() {
        return roleKeyList;
    }

    public void setRoleKeyList(Set<String> roleKeyList) {
        this.roleKeyList = roleKeyList;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
